package com.dys.ai.controller;

import com.dys.ai.common.api.ApiResponse;
import com.dys.ai.common.api.ResponseEntity;
import com.dys.ai.common.exception.CustomException;
import com.dys.ai.common.request.ChangeRequest;
import com.dys.ai.common.request.TicketRequest;
import com.dys.ai.service.TicketService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

/**
 * 购票控制器
 *
 * @author 疾风
 */
@RestController
public class TicketController {

    @Autowired
    private TicketService ticketService;

    @PostMapping("/bookTicketByUserInput")
    public ResponseEntity bookTicketByUserInput(
            @RequestBody TicketRequest request
    ) {
        try {
            return ticketService.butTicketByUserInput(
                    request.getRealName(),
                    request.getDepartureStation(),
                    request.getArrivalStation(),
                    request.getDepartureDate(),
                    request.getTrainNumber(),
                    request.getSeatTypeName()
            );
        } catch (CustomException e) {
            return ApiResponse.error(400, e.getMessage());
        }
    }

    @PostMapping(value = "/changeTicket")
    public ResponseEntity changeTicket(@RequestBody ChangeRequest request) {
        try {
            // 调用服务层处理改签
            return ticketService.changeOrder(
                    request.getOriginalOrderId(),
                    request.getNewTrainId(),
                    request.getNewCarriageNumber(),
                    request.getNewSeatNumber()
            );
        } catch (RuntimeException e) {
            // 统一异常处理（可替换为自定义异常处理机制）
            return ApiResponse.failed(HttpStatus.BAD_REQUEST.value(), "改签失败：" + e.getMessage());
        }
    }

    @GetMapping(value = "/refundTicket/{orderId}")
    public ResponseEntity refundTicket(@PathVariable Long orderId) {
        try {
            // 调用服务层处理改签
            return ticketService.refundOrder(orderId);
        } catch (RuntimeException e) {
            // 统一异常处理（可替换为自定义异常处理机制）
            return ApiResponse.error(HttpStatus.BAD_REQUEST.value(), "退票失败：" + e.getMessage());
        }
    }

    @GetMapping(value = "/listOrders")
    public ResponseEntity listOrders() {
        return ticketService.listOrderInfo();
    }
}
